#include<iostream>
#include<cstring>
#include<queue>

using namespace std;
typedef pair<int,int> PII; 
const int N = 1010;
int m , n;
int p[N][N],r,l;
bool st[N][N];
int dx[] = {0,0,-1,1};
int dy[] = {-1,1,0,0}; 
bool bfs(int mid)
{
	if(n == 1) return true;
	memset(st,0,sizeof st);
	queue<PII> q;
	for(int j = 1; j <= m; j++)
	{
		q.push({1,j});
		st[1][j] = true;
	}

	
	while(q.size())
	{
		auto t = q.front(); q.pop();
		int x = t.first , y = t.second;
		for(int i = 0; i < 4; i++)
		{
			int a = x + dx[i] , b = y + dy[i];
			if(a >= 1 && a <= n && b >= 1 && b <= m && p[a][b] <= mid && st[a][b] == false)
			{
				q.push({a,b});
				st[a][b] = true;
				if(a == n) return true;
			}
			
		} 
	}
	return false;
}
int main()
{
	cin >> n >> m;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= m; j++)
		{
			cin >> p[i][j];
			r = max(r,p[i][j]);
		}
	}
	while(l < r)
	{
		
		int mid = (l + r) / 2;
		if(bfs(mid)) r = mid;
		else l = mid + 1;
	}
	cout << l << endl;
	return 0;
} 
